﻿using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace Ocelot.Admin.Api.Web.Core
{

    public static class ServerExt
    {


        public static void UseHTML(this IApplicationBuilder app)
        {
            //主页是html
            DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
            defaultFilesOptions.DefaultFileNames.Clear();
            //设置首页，我希望用户打开`localhost`访问到的是`wwwroot`下的Index.html文件
            defaultFilesOptions.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(defaultFilesOptions);

            var provider = new FileExtensionContentTypeProvider();
            provider.Mappings[".less"] = "text/css";
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = o =>
                {
                    if (Path.GetExtension(o.File.Name).ToLower() == ".html")
                        o.Context.Response.Headers.Add("cache-control", "no-cache");
                },
                ContentTypeProvider = provider
            });
            try
            {

                //图片文件路径浏览器
                app.UseDirectoryBrowser(new DirectoryBrowserOptions()
                {
                    FileProvider = new PhysicalFileProvider(
                     System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot")
                        ),
                    RequestPath = "/browser"
                });
            }
            catch (Exception ex) { Console.WriteLine(ex); }
        }
    }
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);
            services.AddConfigurableOptions<AppInfoOptions>();
            services.AddRemoteRequest();

            services.AddCorsAccessor();

            services.AddControllers()
                    .AddInjectWithUnifyResult();
          
            services.AddSqlsugarSetup();

            //Http请求
            services.AddRemoteRequest();

            services.AddSignalR();

            services.AddMemoryCache();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseHTML();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
           
            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ConsulHub>("/consulhub");
            });
        }
    }
}